<?php
class ControllerCommonFileManager extends Controller {
    
    public function wxdownload(){

        $image = $this->weixinjs->downloadToUpyun($this->request->get['media_id']);
        
    
        $this->response->setDataResult(1,"",$image);
    }
    
    public function upload()
    {
        if (!$this->customer->isLogged()) {
            $this->response->setDataResult(0,"未登录！",null);
            return;
        }
        
        $this->upload_save('catalog/'.$this->customer->getId().'/');
    }

	protected function upload_save($subdirectory) {

		$directory = rtrim(DIR_IMAGE . $subdirectory, '/');

		if(!file_exists($directory))
		{
		    mkdir($directory);
		}

		if (!empty($this->request->files['file']['name']) && is_file($this->request->files['file']['tmp_name'])) {
		    // Sanitize the filename
		    $filename = basename(html_entity_decode($this->request->files['file']['name'], ENT_QUOTES, 'UTF-8'));
		
		    // Validate the filename length
		    if ((utf8_strlen($filename) < 3) || (utf8_strlen($filename) > 255)) {
		        $this->response->setDataResult(0,"文件名不合法！",null);
		        return;
		    }
		
		    // Allowed file extension types
		    $allowed = array(
		        'jpg',
		        'jpeg',
		        'gif',
		        'png'
		    );
		
		    $sufix = utf8_strtolower(utf8_substr(strrchr($filename, '.'), 1));
		    
		    if (!in_array($sufix, $allowed)) {
		        $this->response->setDataResult(0,"文件后缀不合法！",null);
		        return;
		    }
		
		    // Allowed file mime types
		    $allowed = array(
		        'image/jpeg',
		        'image/pjpeg',
		        'image/png',
		        'image/x-png',
		        'image/gif'
		    );
		
		    if (!in_array($this->request->files['file']['type'], $allowed)) {
		        $this->response->setDataResult(0,"文件格式不合法(type)！",null);
		        return;
		    }
		
		    // Check to see if any PHP files are trying to be uploaded
		    $content = file_get_contents($this->request->files['file']['tmp_name']);
		
		    if (preg_match('/\<\?php/i', $content)) {
		        $this->response->setDataResult(0,"文件格式不合法(content)！",null);
		        return;
		    }
		
		    // Return any upload error
		    if ($this->request->files['file']['error'] != UPLOAD_ERR_OK) {
		        $this->response->setDataResult(0,"文件上传失败！",null);
		        return;
		    }
		} else {
		        $this->response->setDataResult(0,"文件上传失败！",null);
		        return;
		}
		
		$newname = md5( time() .  $this->customer->getId() . rand(1000,9999)) .'.' . $sufix;

		move_uploaded_file($this->request->files['file']['tmp_name'], $directory . '/' . $newname);
		
		$this->response->setDataResult(1,"",$subdirectory . $newname);
		return;
	}
}